package com.spica.platform.uaa.client.model.resolver;

import com.spica.platform.uaa.client.model.ClientQueryParam;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class ClientQueryArgumentResolver implements HandlerMethodArgumentResolver {


    /**
     * 应用标识
     */
    private static final String CLIENT_ID = "clientId";

    /**
     * 资源限定串(逗号分割)
     */
    private static final String RESOURCE_IDS = "resourceIds";
    /**
     * 范围
     */
    private static final String SCOPE = "scope";

    /**
     * 5种oauth授权方式(authorization_code,password,refresh_token,client_credentials)
     */
    private static final String AUTHORIZED_GRANT_TYPES = "authorizedGrantTypes";

    /**
     * 回调地址
     */
    private static final String WEB_SERVER_REDIRECT_URI = "webServerRedirectUri";

    /**
     * 权限
     */
    private static final String AUTHORITIES = "authorities";

    /**
     * access_token有效期
     */
    private static final String ACCESS_TOKEN_VALIDITY =  "accessTokenValidity";

    /**
     * refresh_token有效期
     */
    private static final String REFRESH_TOKEN_VALIDITY = "refreshTokenValidity";

    /**
     *
     */
    private static final String ADDITIONAL_INFORMATION = "additionalInformation";

    /**
     * 是否自动授权 是-true
     */
    private static final String AUTO_APPROVE = "autoapprove";

    /**
     * 关键字查找clientName
     */
    private static final String SEARCH_KEY = "searchKey";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> cla = parameter.getParameterType();

        return cla.isAssignableFrom(ClientQueryParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        ClientQueryParam clientQueryParam = new ClientQueryParam();
        Map<String, String[]> param = request.getParameterMap();
        if (param.containsKey(SEARCH_KEY)) {
            clientQueryParam.setSearchKey(request.getParameter(SEARCH_KEY));
        }
        return clientQueryParam;
    }
}
